<?php
/**
 * Created by PhpStorm.
 * User: tingyugetc
 * Date: 16/12/21
 * Time: 下午3:58
 */

namespace app\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Trade;
use App\Repositories\CategoryRepository;
use App\Repositories\TradeRepository;

use App\Http\Requests\Category\CreateRequest as CateCreateRequest;
use App\Http\Requests\Category\UpdateRequest as CateUpdateRequest;
use App\Http\Requests\Trade\CreateRequest as TradeCreateRequest;
use App\Http\Requests\Trade\UpdateRequest as TradeUpdateRequest;
use Exception;

class TradeController extends Controller
{

    private $pageSize = 10;
    private $tradeRepository;
    private $categoryRepository;

    public function __construct(TradeRepository $tradeRepository, CategoryRepository $categoryRepository) {
        $this->tradeRepository = $tradeRepository;
        $this->categoryRepository = $categoryRepository;
    }

    public function getIndex() {
        $trades = $this->tradeRepository->lists($this->pageSize);
        return admin_view('trade.index', compact('trades'));
    }

    public function getCreate() {
        $categoriesList = $this->categoryRepository->lists();
        $categories = [];
        foreach ($categoriesList as $category) {
            $categories[$category->id] = $category->cate_name;
        }
        return admin_view('trade.create', compact('categories'));
    }


    public function getUpdate($tradeId) {
        $trade = $this->tradeRepository->find($tradeId);
        $categories = $this->categoryRepository->listsByIdKey();
//        return view('admin.trade.create', ['trade' => $trade, 'categories' => $categories]);
        return admin_view('trade.create', compact('trade', 'categories'));
    }


    public function postCreate(TradeCreateRequest $createRequest) {
        if (!$createRequest->hasFile('logo')) {
            throw new Exception('no file found');
        }

        $file = $createRequest->file('logo');
        $mime = 'image/jpeg';
        $ext = $this->checkMime($mime, 'logo');

        $fileName = md5_file($file->getRealPath()) . '.' . $ext;

        $dir = config('trade.logo.storage_path');
        is_dir($dir) || mkdir($dir, 0755, true);

        if (!file_exists($dir . $fileName)) {
            $file->move($dir, $fileName);
        }

        $resourceUrl = config('app.url') . config('trade.logo.prefix') . '/' . $fileName;

        $trade = $this->tradeRepository->store($createRequest);
        $this->tradeRepository->storeLogo($trade->id, $resourceUrl);

        return redirect(admin_url('trade'))->withMessage('创建成功！');
    }

    public function postUpdate(TradeUpdateRequest $updateRequest, $tradeId) {
        $trade = $this->tradeRepository->update($tradeId, $updateRequest);

        if ($updateRequest->hasFile('logo')) {
            $file = $updateRequest->file('logo');
            $mime = 'image/jpeg';
            $ext = $this->checkMime($mime, 'logo');

            $fileName = md5_file($file->getRealPath()) . '.' . $ext;

            $dir = config('trade.logo.storage_path');
            is_dir($dir) || mkdir($dir, 0755, true);

            if (!file_exists($dir . $fileName)) {
                $file->move($dir, $fileName);
            }

            $resourceUrl = config('app.url') . config('trade.logo.prefix') . '/' . $fileName;
            $this->tradeRepository->storeLogo($trade->id, $resourceUrl);
        }

        return redirect(admin_url('trade'))->withMessage('创建成功！');
    }

    public function getCate() {
        $categories = $this->categoryRepository->listsByPage($this->pageSize);
        return admin_view('trade.cate', compact('categories'));
    }

    public function getCreatecate() {
        $categories = $this->categoryRepository->listsByIdKey();
        return admin_view('trade.createcate', compact('categories'));
    }

    public function getUpdatecate($cateId) {
        $category = $this->categoryRepository->find($cateId);
        $categories = $this->categoryRepository->listsByIdKey();
        return admin_view('trade.createcate', compact('category', 'categories'));
    }

    public function postCreatecate(CateCreateRequest $createRequest) {
        $this->categoryRepository->store($createRequest);

        return redirect(admin_url('trade/cate'))->withMessage('创建成功！');
    }

    public function postUpdatecate(CateUpdateRequest $updateRequest, $cateId) {
        $this->categoryRepository->update($cateId, $updateRequest);
        return redirect(admin_url('trade/cate'))->withMessage('创建成功！');
    }

    public function getDestroy($tradeId) {
        $this->tradeRepository->destroy($tradeId);
        return redirect(admin_url('trade'))->withMessage('删除成功');
    }

    public function getDestroycate($cateId) {
        $this->categoryRepository->destroy($cateId);
        return redirect(admin_url('trade/cate'))->withMessage('删除成功');
    }

    protected function checkMime($mime, $type) {
        $allowTypes = config('trade.' . $type . '.allow_types');

        if (!$ext = array_search($mime, $allowTypes)) {
            throw new Exception('Error file type', 422);
        }

        return $ext;
    }

}